package sun.com.dao;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public abstract class dbutil extends HttpServlet {
    public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        String str = req.getParameter("method");
        Class c = this.getClass();
        String parame = "";
        Method method =null;
        try {
            method =  c.getDeclaredMethod(str,ServletRequest.class,ServletResponse.class);
        } catch (NoSuchMethodException e) {
            e.getMessage();
           throw  new RuntimeException("您调用的方法不存在");
        }
        try {
            parame =  (String) method.invoke(this,req,res);
        } catch (Exception e) {
            System.out.println("调用的方法"+str+"出现异常");
            e.printStackTrace();
        }
        /**
         * 获取请求处理方法返回的字符串，他表示请求转发重定向的路径
         * 如果返回的字符串包含:则进行分割得到前缀和后缀，通过前缀判断请求转发还是重定向，后缀表示路径
         * 如果没有进行请求转发
         */
        if(parame==null||parame.trim().isEmpty()){
            return;
        }else {
           if(parame.contains(":")){

               int index = parame.indexOf(":");
               String s=parame.substring(0,index);
               String path=parame.substring(index+1);System.out.println("if");
               if(s.equals("f")){//请求转发
                req.getRequestDispatcher(path).forward(req,res);
               }else if(s.equals("r")){//重定向
                   res.sendRedirect(req.getContextPath()+path);
               }else {
                   throw new RuntimeException("请求失败");
               }
           }else {
               try {
                   req.getRequestDispatcher(parame).forward(req,res);
               }catch (Exception e){
                   throw new RuntimeException("转发失败!!!");
               }

           }
        }

    }
}
